// templates/deliver/pages/location/location.js
import Toast from '@vant/weapp/toast/toast'
import Notify from '@vant/weapp/notify/notify'
import Dialog from '@vant/weapp/dialog/dialog'
import { clearUserLocalStorage, userRequest } from '../../../../utils/util'
import { authorization } from '../../../../utils/location'
// 防抖函数
function debounce(func, delay) {
  let timer = null
  return function () {
    const context = this
    const args = arguments
    clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(context, args)
    }, delay)
  }
}
const app = getApp()
Page({
  data: {
    upload_text: '',
    // buttonDisabled: false,
    id: 0,
    // username: '',
    customer_list: [],
    customer_value: -1,
    search_mobile: '',
    customer_id: 0,
    customer_name: '',
    customer_mobile: '',
    price: '',
    order_no: '',
    view_delivery_man_id: 0,
    view_driver_name: '',
    view_delivery_district_id: 0,
    // value: '', //搜索商户
    checked: true, //默认计费
    tempFilePaths: [],
    customer_remarks: '',
    customer_address: '',
    customer_address_all: [],
    customer_name: '',
    customer_mobile: '',
    address_id: '',
    customer_aftersales: '',
    hj_order_no: '',
    delivery_man_id: '',
    showPicker: false,
    address: '',
  },

  generateOrderNo() {
    const date = new Date();
    const prefix = "RD";
    // 日期部分：年月日（6位）
    const year = date.getFullYear().toString().slice(2); // 2位
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 2位
    const day = date.getDate().toString().padStart(2, '0'); // 2位

    // 时间部分：时（2位）
    const hour = date.getHours().toString().padStart(2, '0'); // 2位

    // 随机数：4位
    const randomPart = Math.floor(Math.random() * 10000).toString().padStart(4, '0'); // 0000 ~ 9999
    const order_no = `${prefix}${year}${month}${day}${hour}${randomPart}`.slice(0, 14)
    return order_no; // 保证14位

    // return `RD${year}${month}${day}${hour}${minute}${randomPart}`.slice(0, 14); // 保证14位
    // const order_no = `RD${formattedDate}${randomNumber.toString().padStart(3, '0')}`
    // return order_no
  },
  onConfirm(event) {
    const { value } = event.detail.value;
    console.log(value)
    this.setData({
      showPicker: false,
      customer_address: value
    });
  },
  showPickerModal() {
    console.log('点击了按钮')
    this.setData({
      showPicker: true
    })
    console.log(this.data.showPicker)
  },
  onCancel(event) {
    console.log('点击了取消')
    console.log(event)
    this.setData({
      showPicker: false
    });
  },
  onCustomerChange: debounce(function (e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail
    console.log(field, value)
    // 使用对象解构动态更新数据
    const data = {}
    data[field] = value
    this.setData(data)
  }, 1000),
  // 管理员审核计费方法
  onChange({ detail }) {
    // 需要手动对 checked 状态进行更新
    this.setData({ checked: detail })
  },
  /**
   * 生命周期函数--监听页面加载
   */

  onLoad(options) {
    console.log(options)
    if (options && options.orderData) {
      const orderData = JSON.parse(decodeURIComponent(options.orderData))
      console.log(orderData)
      if (orderData) {
        let {
          customer_address,
          customer_name,
          customer_mobile,
          customer_remarks,
          price,
          remark,
          hj_order_no
        } = orderData
        price = Math.abs(Number(price)).toFixed(2)
        this.setData({
          customer_address,
          customer_name,
          customer_mobile,
          customer_aftersales: customer_remarks,
          remark,
          price,
          hj_order_no,
          order_no: hj_order_no
        })
      }
    }
    let now = new Date().getTime() / 1000
    let expiration_time = wx.getStorageSync('expiration_time')
    let group = wx.getStorageSync('role')
    console.log('session:', app.session)
    // wx.setStorageSync('viewDeliveryDate', new Date())
    let access_token = app.session.access_token
    let delivery_man_id = app.session.user.delivery_man_id
    let level = wx.getStorageSync('level')
    console.log(app.session.user.delivery_man_id)
    console.log(delivery_man_id)

    // 调用检查登录状态的函数
    this.checkLoginStatus(now, expiration_time, group, level)
    this.setData({
      access_token,
      delivery_man_id,
      level,
      order_no: this.generateOrderNo()
    })
    // this.initData()
    // 提前请求定位授权

  },
  checkLoginStatus(now, expiration_time, group, level) {
    console.log(level)
    console.log(level !== '1' && level !== '9')

    if (group !== '配送司机' || now > expiration_time) {
      let groupName = group.name !== '配送司机' ? '非配送司机角色！' : '已过登录有效期!'
      wx.showToast({
        title: groupName,
        icon: 'error',
        duration: 2000
      })
      app.session = {}
      clearUserLocalStorage()
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/selectID/selectID'
        })
      }, 1000)
    }
  },

  /**
    * 获取当前位置
    */
  async get_current_location() {
    let res = await authorization()
    console.log("authorization res", res);
    this.setData({
      longitude: res.longitude,
      latitude: res.latitude
    })
  },

  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  handleSearch(mobile) {
    this.setData({
      search_mobile: mobile,
      customer_mobile: mobile
    })

    clearTimeout(this.debounceTimeout)
    this.debounceTimeout = setTimeout(() => {
      this.searchCustomer('', mobile)
    }, 1000)
  },
  onCustomerMobileSearchChange(e) {
    let search_mobile = e.detail.replace(/\s+/g, '')
    // 验证手机号格式
    let mobilePattern = /^1[3-9]\d{9}$/
    if (!mobilePattern.test(search_mobile)) {
      Toast.fail('请输入正确的手机号')
      return
    }
    this.handleSearch(search_mobile)
  },

  searchCustomer(customer_name, search_mobile) {
    let that = this
    wx.request({
      url: app.globalData.API + '/delivery/index/search-customer',
      header: {
        'Content-Type': 'application/json',
        'x-api-key': that.data.access_token
      },
      data: {
        customer_name,
        search_mobile
      },
      method: 'POST',
      success: res => {
        if (res.data.code === 200) {
          const success = res.data.data
          console.log(success)
          if (success) {
            let customer_list = res.data.data
            let customer_value = -1
            let customer_id = 0
            let customer_mobile,
              customer_address_all = [],
              customer_aftersales,
              customer_remarks,
              address_id
            if (customer_list && customer_list.length > 0) {
              customer_list = customer_list.map(customer => {
                customer.text = `[Id: ${customer.value}] ${customer.text}`
                return customer
              })
              console.log(customer_list[0].addresses)
              customer_list[0].addresses.forEach(address => {
                console.log(address)
                if (address.location) {
                  customer_address_all.push({ text: address.location, value: address.location })
                } else {
                  customer_address_all.push({
                    text: address.city + address.district + address.detail,
                    value: address.city + address.district + address.detail
                  })
                }
              })
              console.log(customer_address_all)
              customer_value = customer_list[0].value // 将第一个数据显示为选中项
              customer_name = customer_list[0].addresses[0].name
              customer_mobile = customer_list[0].mobile
              customer_id = customer_list[0].value
              address_id = customer_list[0].addresses[0].id
              // customer_address = customer_list[0].addresses[0].location + customer_list[0].addresses[0].detail
            } else {
              customer_mobile = search_mobile
            }
            that.setData({
              customer_list: customer_list,
              customer_value: customer_value,
              customer_id,
              customer_name,
              customer_mobile,
              customer_address_all,
              customer_aftersales,
              customer_remarks,
              address_id
            })
          }
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },
  // 新增表单验证方法
  on_dropdown_change(e) {
    this.setData({
      customer_address: e.detail
    })
    // this.reLoad()
  },
  async formSubmit(e) {
    // 获取必要数据
    // console.log(e.currentTarget.dataset.order_no)
    // wx.navigateTo({
    //   url: `/templates/deliver/pages/print_after_sales/print_after_sales?order_no=${e.currentTarget.dataset.order_no}`
    // })
    // return
    const {
      delivery_man_id,
      order_no,
      customer_name,
      customer_mobile,
      customer_id,
      price,
      tempFilePaths,
      access_token,
      customer_address,
      customer_aftersales,
      customer_remarks,
      address_id,
      hj_order_no
    } = this.data
    console.log(price)
    if (price <= 0) {
      wx.showToast({
        title: '请输入商户金额',
        icon: 'none'
      }).then(() => {
        // on close
        console.log('then')
      })
      return
    }
    // if (customer_address === '' || customer_status === '' || customer_aftersales === '' || customer_remarks === '') {
    //     wx.showToast({
    //         title: '请填写所有必填字段',
    //         icon: 'none'
    //     });
    //     return;
    // }
    console.log(customer_address, customer_aftersales, customer_remarks)
    if (tempFilePaths.length === 0) {
      Toast.fail('请先拍照或者选择照片~~')
      return
    }
    try {
      // 显示加载提示
      wx.showLoading({
        title: '加载中...'
      })
      console.log(tempFilePaths[0].url)
      const imageResponse = await this.uploadImage(tempFilePaths[0].url, access_token)
      if (imageResponse.code !== 200) throw new Error('图片上传失败')
      console.log(imageResponse.data.id)
      console.log(imageResponse.data.url)
      // 创建订单
      const orderResponse = await this.createOrder(
        {
          order_no,
          customer_name,
          customer_mobile,
          customer_id,
          price,
          delivery_man_id,
          address: customer_address,
          customer_remark: customer_aftersales,
          remark: customer_remarks,
          image_id: imageResponse.data.id,
          image_url: imageResponse.data.url,
          address_id,
          hj_order_no
        },
        access_token
      )
      wx.hideLoading()
      if (orderResponse.data.code == 200) {
        // Toast.success('订单添加完成')
        setTimeout(() => {
          wx.navigateTo({
            url: `/templates/deliver/pages/print_after_sales/print_after_sales?order_no=${e.currentTarget.dataset.order_no}`
          })
          // wx.navigateBack({ delta: 1 })
        }, 1000)
      } else {
        Toast.fail(orderResponse.data.msg)
        throw new Error('订单创建失败')
        return false
      }
      // if (orderResponse.code !== 200)
      //     this.setData({ 'upload_text': '上传成功' });

      // Notify({ type: 'success', message: '订单添加完成' });
    } catch (error) {
      console.error('提交失败:', error)
      Toast.fail('提交失败，请重试')
    }
  },
  // 提取上传图片方法
  async uploadImage(filePath, access_token) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'https://helper.fuduoduoshop.com/api/v1/file/images',
        filePath: filePath,
        header: {
          'Content-Type': 'application/json',
          'x-api-key': access_token
        },
        name: 'file',
        formData: {
          drive: 'qiniu',
          thumb: JSON.stringify([{ width: 100, height: 100 }])
        },
        success: res => {
          const response = JSON.parse(res.data)
          resolve(response)
        },
        fail: reject
      })
    })
  },
  // 提取创建订单方法
  async createOrder(orderData, access_token) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.globalData.API + '/delivery/index/add-after-market-delivery-order',
        header: {
          'Content-Type': 'application/json',
          'x-api-key': access_token
        },
        method: 'POST',
        data: {
          ...orderData,
          channel_id: app.globalData.mall_id
        },
        success: resolve,
        fail: reject
      })
    })
  },
  formatTime(date) {
    const pad = n => n.toString().padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
  },
  /* 上传文件后事件，处理照片放入OSS回显 */
  async afterRead(event) {
    let that = this
    const { file } = event.detail
    console.log(event)
    console.log(this.data.tempFilePaths)
    this.setData({
      tempFilePaths: [...this.data.tempFilePaths, { url: file.url }]
    })
    // 获取当前位置
    await this.get_current_location();
    // 格式化时间

    // this.unloadImage(file.path)
    for (let i = 0; i < file.length; i++) {
      wx.uploadFile({
        url: 'https://helper.fuduoduoshop.com/api/v1/file/images',
        filePath: file[i]['url'], //传递文件
        header: {
          'Content-Type': 'application/json',
          'x-api-key': that.data.access_token
        },
        name: 'file', //获取照片信息的名称
        formData: {
          drive: 'qiniu',
          thumb: JSON.stringify([
            {
              width: 100,
              height: 100
            }
          ])
        },

        success(res) {
          let response = JSON.parse(res.data) //传过来的是json 需要转换成对象
          let code = response.code
          if (code === 200) {
            const { tempFilePaths = [] } = that.data
            tempFilePaths.push({ ...file, url: response.data.url })
            that.setData({
              tempFilePaths
            })
          }
        }
      })
    }

  },
  // 获取位置和时间
  // async afterRead(event) {
  //   let that = this
  //   const { file } = event.detail
  //   console.log(event)
  //   console.log(this.data.tempFilePaths)

  //   // 获取当前位置
  //   await this.get_current_location();
  //   // 格式化时间
  //   const date = new Date();
  //   const time = this.formatTime(date);
  //   // 获取位置信息
  //   const { longitude, latitude } = this.data;
  //   let address = '';
  //   if (longitude && latitude) {
  //     try {
  //       const res = await new Promise((resolve, reject) => {
  //         wx.request({
  //           url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=ANNBZ-KHK35-WPKIX-I2FVZ-PLPI2-RYB6J`,
  //           success: (res) => {
  //             if (res.data.status === 0) {
  //               resolve(res.data.result.address);
  //             } else {
  //               reject(new Error('逆地理编码失败'));
  //             }
  //           },
  //           fail: (err) => {
  //             reject(err);
  //           }
  //         });
  //       });
  //       address = res;
  //     } catch (err) {
  //       console.error('获取位置信息失败', err);
  //     }
  //   }
  //   // 创建 canvas 上下文
  //   const ctx = wx.createCanvasContext('watermarkCanvas');
  //   // 绘制图片
  //   ctx.drawImage(file.url, 0, 0, 300, 300);
  //   // 设置水印文字样式
  //   ctx.setFontSize(14);
  //   ctx.setFillStyle('rgba(255, 255, 255, 0.8)');
  //   // 添加位置水印
  //   if (address) {
  //     ctx.fillText(`地址: ${address}`, 10, 260);
  //   }
  //   // if (longitude && latitude) {
  //   //   ctx.fillText(`位置: ${latitude}, ${longitude}`, 10, 280);
  //   // }
  //   // 添加时间水印
  //   ctx.fillText(`时间: ${time}`, 10, 300);

  //   // 绘制到 canvas
  //   ctx.draw(false, () => {
  //     // 将 canvas 转换为临时文件路径
  //     wx.canvasToTempFilePath({
  //       canvasId: 'watermarkCanvas',
  //       success: (res) => {
  //         const watermarkedFile = { url: res.tempFilePath };
  //         that.setData({
  //           tempFilePaths: [...that.data.tempFilePaths, watermarkedFile]
  //         });

  //         // 上传带水印的图片
  //         wx.uploadFile({
  //           url: 'https://helper.fuduoduoshop.com/api/v1/file/images',
  //           filePath: watermarkedFile.url,
  //           header: {
  //             'Content-Type': 'application/json',
  //             'x-api-key': that.data.access_token
  //           },
  //           name: 'file',
  //           formData: {
  //             drive: 'qiniu',
  //             thumb: JSON.stringify([
  //               {
  //                 width: 100,
  //                 height: 100
  //               }
  //             ])
  //           },
  //           success: (res) => {
  //             let response = JSON.parse(res.data);
  //             let code = response.code;
  //             if (code === 200) {
  //               const { tempFilePaths = [] } = that.data;
  //               tempFilePaths.push({ ...watermarkedFile, url: response.data.url });
  //               that.setData({
  //                 tempFilePaths
  //               });
  //             }
  //           }
  //         });
  //       },
  //       fail: (err) => {
  //         console.error('生成带水印图片失败', err);
  //         // 若失败，上传原始图片
  //         that.setData({
  //           tempFilePaths: [...that.data.tempFilePaths, { url: file.url }]
  //         });
  //         wx.uploadFile({
  //           url: 'https://helper.fuduoduoshop.com/api/v1/file/images',
  //           filePath: file.url,
  //           header: {
  //             'Content-Type': 'application/json',
  //             'x-api-key': that.data.access_token
  //           },
  //           name: 'file',
  //           formData: {
  //             drive: 'qiniu',
  //             thumb: JSON.stringify([
  //               {
  //                 width: 100,
  //                 height: 100
  //               }
  //             ])
  //           },
  //           success: (res) => {
  //             let response = JSON.parse(res.data);
  //             let code = response.code;
  //             if (code === 200) {
  //               const { tempFilePaths = [] } = that.data;
  //               tempFilePaths.push({ ...file, url: response.data.url });
  //               that.setData({
  //                 tempFilePaths
  //               });
  //             }
  //           }
  //         });
  //       }
  //     });
  //   });
  // },
  imgDelete(event) {
    let that = this
    let urlPath = event.detail.file.url
    wx.request({
      url: app.globalData.API + '/delivery/index/delete-qiniu-image',
      header: {
        'Content-Type': 'application/json',
        'x-api-key': that.data.access_token
      },
      data: {
        path: urlPath
      },
      method: 'POST',
      success: res => {
        if (res.data.code === 200) {
          const success = res.data.data
          console.log(success)
          if (success) {
            let tempFilePaths = that.data.tempFilePaths
            tempFilePaths = tempFilePaths.filter(item => item.url !== urlPath)
            that.setData({
              tempFilePaths
            })
          }
        }
      }
    })
  },
  imgSize(event) {
    let imgMax = this.data.address_image_max_size //获取默认上传文件大小
    const { file } = event.detail //获取上传文件数组
    for (let i = 0; i < file.length; i++) {
      if (file[i].size > imgMax) {
        Toast('大小超过2MB~')
      }
    }
  }
})
